<?php

namespace app\admin\controller;

use think\facade\Db;
use WpOrg\Requests\Utility\InputValidator;

class Bew extends Base
{

    public function menuLists()
    {

        #1.把菜单全部查询出来，父菜单在前面,parent_id 从小到大升序，sort从大到小倒叙
        $lists = Db::table('bew_admin_sys_menu')->order('parent_id ACS,sort DESC')->select()->toArray();
        if (empty($lists)) {
            $this->returnCode(1, '未找到数据');
        }
        foreach ($lists as $lists_v) {
            $list_v['key'] = $lists_v['mid'];
            if ($lists_v['status'] == 1) {
                $lists_v['status_s'] = '开启';
            } else {
                $list_v['status_s'] = '关闭';
            }
            if ($lists_v['type'] == 0) {
                $lists_v['type_s'] = '分组';
            } elseif ($list_v['type'] == 1) {
                $lists_v['type_s'] = '模块';
            } elseif ($lists_v['type'] == 2) {
                $lists_v['type_s'] = '超链接';
            }

            #2.把处理后的数据，传值新数组
            // 2.1子菜单。先找到父菜单，在放到son下标里
            if ($lists_v['parent_id'] == 0) {
                $tmp[$lists_v['mid']] = $lists_v;
            } else {
                $tmp[$lists_v['parent_id']]['son'][] = $lists_v;
            }
        }
        $arr = [
            'lists' => array_merge($tmp)
        ];
        echo json_encode(['code' => 0, 'data' => $arr]);
    }

    #2创建 menusave方法
    public function menusave()
    {
        $data['parent_id'] = trim(input('post.parent_id', 0));
        $data['label'] = trim(input('post.label'));
        if (!$data['label']) {
            echo json_encode(['code' => 1, 'msg' => '请输入菜单名']);
            exit;
        }
        $data['type'] = trim(input('post.type', 0));
        if ($data['type'] != 0) {
            $data['src'] = trim(input('post.src'));
        } else {
            $data['src'] = '';
        }

        $data['icon_class'] = trim(input('post.icon_class'));
        $data['sort'] = trim(input('post.sort', 0));
        $data['status'] = trim(input('post.status'), 1);

        $res = Db::table('bew_admin_sys_menu')->insert($data);

        if (!$res) {
            echo json_encode(['code' => 1, 'msg' => '添加失败']);
            exit;
        }

        echo json_encode(['code' => 0, 'msg' => '添加成功']);
    }

    #3.删除
    public function menudel()
    {
        $mid = (int)input('post.mid');
        $menu = Db::table('bew_admin_sys_menu')->where('parent_id', $mid)->find();

        if (!empty($menu)) {
            echo json_encode(['code' => 1, 'msg' => '删除失败']);
            exit;
        }
        $res = Db::table('bew_admin_sys_menu')->where('mid', $mid)->delete();
        if (empty($res)) {
            echo json_encode(['code' => 1, 'msg' => '删除失败']);
            exit;
        }
        echo json_encode(['code' => 0, 'msg' => '成功']);
    }
}
